package com.levi.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author shentong
 * @date 2021/10/26 21:08
 * @Description TODO
 * FIXME @EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true) 开启方法授权 可以使用 @PreAuthorize 注解
 *
 *
 */
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true) //开启方法授权注解
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/r/**").authenticated()
//                .antMatchers("/r/r1").hasAnyAuthority("p1")//配置有p1权限可以访问
//                .antMatchers("/r/r2").hasAnyAuthority("p2")//配置有p2权限可以访问
                .anyRequest().permitAll()//除了上面的需要权限，其他的都不要权限
                .and()
                .formLogin()//允许表单登录
                .loginProcessingUrl("/login")
                .loginPage("/login.html")
                .successForwardUrl("/loginSucess")//登陆成功跳转
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)//如果需要就创建一个Session（默认）登录时
                .maximumSessions(1)//允许同时在一台设备登录，踢掉前面登录的用户，原理是清空之前登录用户的session
                ;
    }

    /**
     * 把用户信息存入内存当中
     * @return
     */
//    @Bean
//    public UserDetailsService userDetailsService() {
//        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
//        manager.createUser(User.withUsername("zhangsan").password("123").authorities("p1").build());
//        manager.createUser(User.withUsername("lisi").password("123").authorities("p2").build());
//        return manager;
//    }

    /**
     * 密码编码方式:这里为了方便测试，使用字符串比较的方式
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
}
